package com.hpu.service;

import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hpu.callback.EncryptCallBack;

/**
 * 加密业务类，该加密业务类必须依托于WebView控件以及demo.html加密文件才可执行，
 * 加密完成后会回调EncryptCallBack对象
 * @author Administrator
 *
 */
public class EncryptService{

	/**
	 * 调用js方法（4.4之上）
	 * @param webView
	 * @param pw
	 * @param callBack
	 */
	@TargetApi(Build.VERSION_CODES.KITKAT)
	private static void callEvaluateJavascript(WebView webView, String pw, final EncryptCallBack callBack) {
		// 调用html页面中的js函数update
		webView.evaluateJavascript("doEncrypt('" + pw + "')", new ValueCallback<String>() {
			@Override
			// value就是调用的函数的返回值
			public void onReceiveValue(String value) {
				value = value.replaceAll("\"", "");
				callBack.onFinish(value);
			}
		});
	}

	/**
	 * 4.4之下的调用js方法
	 * @param webView
	 * @param pw
	 * @param callBack
	 */
	private static void callMethod(WebView webView, String pw, final EncryptCallBack callBack) {
		String encryptPw = "javascript:doEncrypt('" + pw + "')";
		encryptPw = encryptPw.replaceAll("\"", "");
		callBack.onFinish(encryptPw);
	}
	
	public void doEncrypt(final WebView webView,final String pw,final EncryptCallBack encryptCallBack) {
		//加载网页加密
		webView.loadUrl("file:///android_asset/demo.html");
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);// 设置JS可用
		webView.setWebChromeClient(new WebChromeClient() {
		});
		
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
					callEvaluateJavascript(webView, pw, encryptCallBack);
				} else { // 当Android SDK < 4.4时
					callMethod(webView, pw, encryptCallBack);
				}
			}
		});
	}

}
